#include "DatabaseManager.h"
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QStandardPaths>
#include <QDir>
#include <QDebug>

DatabaseManager::DatabaseManager(QObject* parent)
    : QObject(parent)
    , m_isConnected(false)
{
    // 注册SQLite驱动
    QSqlDatabase::addDatabase("QSQLITE");
}

DatabaseManager::~DatabaseManager()
{
    close();
}

DatabaseManager& DatabaseManager::getInstance()
{
    static DatabaseManager instance;
    return instance;
}

bool DatabaseManager::initialize()
{
    // 拼接数据库路径
    QString fullPath = QDir::currentPath() + "/data.db";
    bool dbExists = QFile::exists(fullPath);   // 判断文件是否已存在

    {
        QMutexLocker locker(&m_mutex);   // 锁住连接过程
        if (m_isConnected)
            close();

        QString connectionName = QString("DatabaseConnection_%1")
                                     .arg(QDateTime::currentMSecsSinceEpoch());
        m_database = QSqlDatabase::addDatabase("QSQLITE", connectionName);
        m_database.setDatabaseName(fullPath);

        if (!m_database.open()) {
            m_lastError = QString("无法打开数据库: %1").arg(m_database.lastError().text());
            qWarning() << m_lastError;
            return false;
        }
        m_isConnected = true;

        QSqlQuery query(m_database);
        query.exec("PRAGMA foreign_keys=ON");
        query.exec("PRAGMA journal_mode=WAL");
        query.exec("PRAGMA synchronous=NORMAL");
        query.exec("PRAGMA cache_size=10000");
        query.exec("PRAGMA temp_store=MEMORY");
    } // 这里 locker 作用域结束，锁已释放

    // 如果是新建的数据库，需要创建必要的表
    if (!dbExists) {
        if (!createRequiredTables()) {
            qWarning() << "创建必要表失败:" << m_lastError;
            return false;
        }
    }

    return true;
}



void DatabaseManager::close()
{
    QMutexLocker locker(&m_mutex);
    
    if (m_isConnected && m_database.isOpen()) {
        m_database.close();
        m_isConnected = false;
        qDebug() << "数据库连接已关闭";
    }
}

bool DatabaseManager::isConnected() const
{
    QMutexLocker locker(&m_mutex);
    return m_isConnected && m_database.isOpen();
}

QSqlQuery DatabaseManager::executeQuery(const QString& queryString)
{
    QMutexLocker locker(&m_mutex);
    
    if (!m_isConnected) {
        m_lastError = "数据库未连接";
        qWarning() << m_lastError;
        return QSqlQuery();
    }
    
    QSqlQuery query(m_database);
    if (!query.exec(queryString)) {
        m_lastError = QString("查询执行失败: %1").arg(query.lastError().text());
        qWarning() << m_lastError << "SQL:" << queryString;
    }
    
    return query;
}

bool DatabaseManager::executeQuery(const QString& queryString, QSqlQuery& query)
{
    QMutexLocker locker(&m_mutex);
    
    if (!m_isConnected) {
        m_lastError = "数据库未连接";
        qWarning() << m_lastError;
        return false;
    }
    
    query = QSqlQuery(m_database);
    if (!query.exec(queryString)) {
        m_lastError = QString("查询执行失败: %1").arg(query.lastError().text());
        qWarning() << m_lastError << "SQL:" << queryString;
        return false;
    }
    
    return true;
}

bool DatabaseManager::createTable(const QString& tableName, const QString& columns)
{
    QString queryString = QString("CREATE TABLE IF NOT EXISTS %1 (%2)").arg(tableName, columns);
    QSqlQuery query = executeQuery(queryString);
    return !query.lastError().isValid();
}

bool DatabaseManager::createRequiredTables()
{
    if (!createTable("SidePlate",
                     "id INTEGER PRIMARY KEY AUTOINCREMENT, "
                     "sideplate_code TEXT NOT NULL UNIQUE")) {
        m_lastError = "创建侧板表失败";
        return false;
    }

    if (!createTable("Mould",
                     "id INTEGER PRIMARY KEY AUTOINCREMENT, "
                     "upper_id INTEGER, "
                     "lower_id INTEGER, "
                     "mould_code TEXT NOT NULL UNIQUE, "
                     "FOREIGN KEY (upper_id) REFERENCES SidePlate(id), "
                     "FOREIGN KEY (lower_id) REFERENCES SidePlate(id)")) {
        m_lastError = "创建模具表失败";
        return false;
    }

    if (!createTable("Block",
                     "id INTEGER PRIMARY KEY AUTOINCREMENT, "
                     "block_code TEXT NOT NULL UNIQUE")) {
        m_lastError = "创建 Block 表失败";
        return false;
    }

    if (!createTable("MouldBlock",
                     "id INTEGER PRIMARY KEY AUTOINCREMENT, "
                     "mould_id INTEGER NOT NULL, "
                     "block_id INTEGER NOT NULL, "
                     "FOREIGN KEY (mould_id) REFERENCES Mould(id) ON DELETE CASCADE, "
                     "FOREIGN KEY (block_id) REFERENCES Block(id),"
                     "UNIQUE(mould_id, block_id)")) {
        m_lastError = "创建 MouldBlock 表失败";
        return false;
    }

    if (!createTable("Construction",
                     "id INTEGER PRIMARY KEY AUTOINCREMENT, "
                     "mould_id INTEGER NOT NULL, "
                     "construction_id INTEGER NOT NULL, "
                     "upper_block_id INTEGER NOT NULL, "
                     "lower_block_id INTEGER NOT NULL, "
                     "FOREIGN KEY (mould_id) REFERENCES Mould(id) ON DELETE CASCADE, "
                     "FOREIGN KEY (upper_block_id) REFERENCES Block(id),"
                     "FOREIGN KEY (lower_block_id) REFERENCES Block(id),"
                     "UNIQUE (construction_id, mould_id)")) {
        m_lastError = "创建 Construction 表失败";
        return false;
    }

    return true;
}

QString DatabaseManager::getLastError()
{
    return m_lastError;
}

